import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/api/user'
import { usePermissionStore } from './permission'

interface ResponseData{
  code?: number
  message?: string
  data?:{}
}

interface LoginData {
  username: string
  password: string
  rememberMe: boolean
  code: string
  code_key: string
}

interface LoginResponseData {
  id?: number
  username?: string
  access_token?: string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref()
  const token = ref<string | null>(null)
  const isAuthenticated = computed(() => !!token.value)

  // 从缓存初始化状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token') || sessionStorage.getItem('token')
    const savedUser = localStorage.getItem('user') || sessionStorage.getItem('user')
    
    if (savedToken && savedUser) {
      token.value = savedToken
      user.value = JSON.parse(savedUser)
    }
  }

  // 登录
  const login = async (loginData: LoginData): Promise<ResponseData> => { 
    try {
      let json = {
            username: loginData.username,
            password: loginData.password,
            code: loginData.code,
            code_key: loginData.code_key
          }

      const response = await userApi.login(json);
      if(response.code == 200){
        user.value = response.data
        const userData: LoginResponseData = response.data
        const access_token = userData.access_token||'';
        localStorage.setItem('token', access_token)
        localStorage.setItem('user', JSON.stringify(user.value))
        localStorage.setItem('userId', user.value.id)
        // 登录成功后获取权限
        const permissionStore = usePermissionStore()
        await permissionStore.fetchPermissions(user.value.id)
      
        // 初始化
        initAuth()
      
      }
      return response
    } catch (error) {
      throw error
    } 
  }

  // 登出
  const logout = (): void => {
    user.value = null
    token.value = null
    
    // 清除所有存储的认证信息
    localStorage.clear()
    sessionStorage.clear()
  }

 
  initAuth()

  return {
    user,
    token,
    isAuthenticated,
    login,
    logout,
    initAuth
  }
})